package com.baidu.shopping.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.baidu.app.dao.AppMapper;
import com.baidu.app.pojo.App;
import com.baidu.shopping.dao.ShoppingDaoI;
import com.baidu.shopping.dao.ShoppingMapper;
import com.baidu.shopping.pojo.Cart;
import com.baidu.shopping.pojo.CartItem;
import com.baidu.shopping.pojo.Order;
import com.baidu.shopping.pojo.OrderItem;
import com.baidu.user.dao.UserMapper;
import com.baidu.user.pojo.User;

@Service
public class ShoppingServiceImpl implements ShoppingServiceI {
	
	@Autowired
	@Qualifier("shoppingDaoImpl")
	private ShoppingDaoI dao;
	
	@Autowired
	private AppMapper mapper;
	
	@Autowired
	private ShoppingMapper shoppingMapper;
	
	

	@Override
	public App getAppById(String appid) {
		
		return mapper.getAppById(appid);
	}

	@Override
	public boolean addAppIntoCart(Cart cart) {
		
		return dao.addAppIntoCart(cart);
	}

	@Override
	public Cart getCartById(String ip) {
	
		return dao.getCartById(ip);
	}

	@Override
	public User login(User user) {
		
		return shoppingMapper.login(user);
	}




	@Override
	public String addOrder(User user, String address, String[] appid) {
		
        Cart cart = dao.getCartById(user.getId());
		
	    Order order = new Order();
	    order.setId(System.currentTimeMillis() + "");
	    order.setUserid(user.getId());
	    double totalPrice = 0.0;
	    for (String string : appid) {
			CartItem cartItem = cart.getCart().get(string);
			totalPrice += cartItem.getTotalPrice();
		}
	    order.setTotalpay(totalPrice);
	    order.setStatus(0);
	    order.setAddress(address);
	    order.setCtime(new Date());
	    order.setPhone(user.getPhone());	
		shoppingMapper.insertSelective(order);

			
		for (String string : appid) {
			 CartItem cartItem = cart.getCart().get(string);
			 OrderItem orderItem = new OrderItem();
			 orderItem.setId(System.currentTimeMillis() + "");
			 orderItem.setOrderid(order.getId());
			 orderItem.setAppname(cartItem.getApp().getAppname());
			 orderItem.setPrice(cartItem.getApp().getPrice());
			 orderItem.setBuynum(cartItem.getBuyNum());
			 orderItem.setCountpay(cartItem.getTotalPrice());
			 shoppingMapper.addOrderItem(orderItem);
		}
		
		for (String string : appid) {
			cart.remove(string);
		}
		dao.addAppIntoCart(cart);
		
		 return order.getId();
	}

	
	@Override
	public List<OrderItem> getOrderitem(String orderid) {
		
		return shoppingMapper.getOrderitem(orderid);
	}
	
	
	

	


}
